#include "Sequential_Queue.h"

int Sequential_queue_init(Sequential_queue_t ** queue,int len){
    if(*queue!=NULL){
        return -1;
    }
    (*queue) = (Sequential_queue_t *)malloc(sizeof(Sequential_queue_t));
    if(*queue==NULL){
        LOG("queue create failed\n");
        return -1;
    }
    (*queue)->data = (int *)malloc(sizeof(int)*len);
    if((*queue)->data == NULL){
        LOG("queue data create failed\n");
        return -1;
    }

    (*queue)->len = len;
    (*queue)->font = 0;
    (*queue)->rear = 0;
    return 0;
}

static int Sequential_queue_isFull(Sequential_queue_t * queue){
    if((queue->rear+1)%queue->len == queue->font){
        LOG("queue is full\n");
        return 0;
    }
    return -1;
}

static int Sequential_queue_isNull(Sequential_queue_t * queue){
    if(queue->rear == queue->font){
        LOG("queue is null\n");
        return 0;
    }
    return -1;
}

int Sequential_queue_enqueue(Sequential_queue_t * queue,int data){
    if(queue==NULL){
        return -1;
    }
    if(Sequential_queue_isFull(queue)==0){
        return -1;
    }
    if(Sequential_queue_isNull(queue)==0){
        queue->data[queue->font] = data;
    }else{
        queue->data[queue->rear] = data;
    }
    queue->rear = (queue->rear+1)%queue->len;
    return 0;
}

int Sequential_queue_dequeue(Sequential_queue_t * queue,int *data){
    if(Sequential_queue_isNull(queue)==0){
        return -1;
    }
    *data = queue->data[queue->font];
    queue->data[queue->font] = 0;
    queue->font = (queue->font+1)%queue->len;
    return 0;
}

int Sequential_queue_select(Sequential_queue_t * queue){
    int i = 0;
    for(i=0;i<queue->len;i++){
        printf("[%d]%d->",i,queue->data[i]);
    }
    printf("\n");
    return 0;
}

int Sequential_queue_destory(Sequential_queue_t * queue){
    if(queue==NULL){
        return -1;
    }
    free(queue->data);
    queue->data = NULL;
    free(queue);
    queue = NULL;
    return 0;
}